1. 题目

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

1

/ \
2 2
/ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:

1

/ \
2 2
\
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.

2. 思路

最简单的方式递归比较左、右子树。两个子树A和B的比较是A的左子树和B的右子树符合镜像。A的右子树和B的左子树符合镜像。

迭代的方案是,用两个站来分别遍历左、右子树,一个左中右,一个右中左的顺序。

3. 代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        return root == NULL ? true : isMirror(root->left, root->right);
    }
    
    bool isMirror(TreeNode* n1, TreeNode* n2) {
        if (n1 == NULL && n2 == NULL) { return true; }
        if (n1 == NULL || n2 == NULL) { return false; }
        return n1->val == n2->val && isMirror(n1->left, n2->right) && isMirror(n1->right, n2->left);
    }
};

knzeus
72 声望28 粉丝

行万里路,读万卷书